<template>
  <div class="user-management">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">
          <i class="el-icon-user"></i>
          用户管理
        </h2>
        <span class="page-subtitle">管理系统用户账号和权限</span>
      </div>
      <div class="header-actions">
        <el-button 
          type="primary" 
          icon="el-icon-plus" 
          @click="handleAdd" 
          v-if="hasPermission('system:user:add')"
          size="medium"
        >
          新增用户
        </el-button>
        <el-button 
          icon="el-icon-download" 
          @click="handleExport" 
          v-if="hasPermission('system:user:export')"
          size="medium"
        >
          导出数据
        </el-button>
        <el-button 
          icon="el-icon-upload2" 
          @click="handleImport" 
          v-if="hasPermission('system:user:import')"
          size="medium"
        >
          批量导入
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-card shadow="never" class="search-card">
        <el-form :model="searchForm" :inline="true" class="search-form">
          <el-form-item label="关键词">
            <el-input
              v-model="searchForm.keyword"
              placeholder="用户名/姓名/邮箱"
              clearable
              prefix-icon="el-icon-search"
              @keyup.enter.native="handleSearch"
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="部门">
            <el-select 
              v-model="searchForm.department" 
              placeholder="请选择部门" 
              clearable
              style="width: 150px"
            >
              <el-option label="技术部" value="技术部" />
              <el-option label="行政部" value="行政部" />
              <el-option label="财务部" value="财务部" />
              <el-option label="人事部" value="人事部" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="searchForm.status" 
              placeholder="请选择状态" 
              clearable
              style="width: 120px"
            >
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">
              搜索
            </el-button>
            <el-button icon="el-icon-refresh" @click="handleReset">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-section">
      <el-card shadow="never" class="table-card">
        <!-- 表格工具栏 -->
        <div class="table-toolbar">
          <div class="toolbar-left">
            <span class="table-title">用户列表</span>
            <el-tag v-if="selectedRows.length > 0" type="info" size="small">
              已选择 {{ selectedRows.length }} 项
            </el-tag>
          </div>
          <div class="toolbar-right">
            <el-button 
              size="small" 
              icon="el-icon-refresh" 
              @click="loadData"
              :loading="loading"
            >
              刷新
            </el-button>
          </div>
        </div>

        <!-- 数据表格 -->
        <el-table
          :data="tableData"
          v-loading="loading"
          @selection-change="handleSelectionChange"
          stripe
          border
          height="500"
          class="data-table"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="username" label="用户名" width="120" show-overflow-tooltip />
          <el-table-column prop="name" label="姓名" width="100" show-overflow-tooltip />
          <el-table-column prop="email" label="邮箱" width="180" show-overflow-tooltip />
          <el-table-column prop="phone" label="手机号" width="120" show-overflow-tooltip />
          <el-table-column prop="department" label="部门" width="100" show-overflow-tooltip />
          <el-table-column prop="position" label="职位" width="100" show-overflow-tooltip />
          <el-table-column prop="employeeId" label="员工ID" width="100" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="80" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
                {{ scope.row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160" show-overflow-tooltip />
          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template slot-scope="scope">
              <el-button 
                size="mini" 
                icon="el-icon-view" 
                @click="handleView(scope.row)" 
                v-if="hasPermission('system:user:list')"
                type="text"
              >
                查看
              </el-button>
              <el-button 
                size="mini" 
                icon="el-icon-edit" 
                @click="handleEdit(scope.row)" 
                v-if="hasPermission('system:user:edit')"
                type="text"
              >
                编辑
              </el-button>
              <el-button
                size="mini"
                :icon="scope.row.status === 1 ? 'el-icon-lock' : 'el-icon-unlock'"
                @click="handleToggleStatus(scope.row)"
                v-if="hasPermission('system:user:edit')"
                :type="scope.row.status === 1 ? 'warning' : 'success'"
                style="text-decoration: none"
              >
                {{ scope.row.status === 1 ? '禁用' : '启用' }}
              </el-button>
              <el-button 
                size="mini" 
                icon="el-icon-delete" 
                @click="handleDelete(scope.row)" 
                v-if="hasPermission('system:user:delete')"
                type="text"
                style="color: #f56c6c"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.size"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            background
          />
        </div>
      </el-card>
    </div>

    <!-- 批量操作 -->
    <div class="batch-actions" v-if="selectedRows.length > 0">
      <el-card shadow="never" class="batch-card">
        <div class="batch-content">
          <span class="batch-info">
            <i class="el-icon-info"></i>
            已选择 {{ selectedRows.length }} 个用户
          </span>
          <div class="batch-buttons">
            <el-button 
              type="success" 
              icon="el-icon-check" 
              @click="handleBatchEnable" 
              v-if="hasPermission('system:user:edit')"
              size="small"
            >
              批量启用
            </el-button>
            <el-button 
              type="warning" 
              icon="el-icon-close" 
              @click="handleBatchDisable" 
              v-if="hasPermission('system:user:edit')"
              size="small"
            >
              批量禁用
            </el-button>
            <el-button 
              type="danger" 
              icon="el-icon-delete" 
              @click="handleBatchDelete" 
              v-if="hasPermission('system:user:delete')"
              size="small"
            >
              批量删除
            </el-button>
            <el-button 
              icon="el-icon-close" 
              @click="selectedRows = []"
              size="small"
            >
              取消选择
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="form"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="formData.username" :disabled="isEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="formData.phone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门" prop="department">
              <el-input v-model="formData.department" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="formData.position" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="员工ID" prop="employeeId">
              <el-input v-model="formData.employeeId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status">
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="formData.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="formData.roleIds" multiple placeholder="请选择角色">
            <el-option
              v-for="role in roleOptions"
              :key="role.id"
              :label="role.roleName"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog
      title="用户详情"
      :visible.sync="detailDialogVisible"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户名">{{ currentUser.username }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ currentUser.name }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ currentUser.email }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ currentUser.phone }}</el-descriptions-item>
        <el-descriptions-item label="部门">{{ currentUser.department }}</el-descriptions-item>
        <el-descriptions-item label="职位">{{ currentUser.position }}</el-descriptions-item>
        <el-descriptions-item label="员工ID">{{ currentUser.employeeId }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentUser.status === 1 ? 'success' : 'danger'">
            {{ currentUser.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentUser.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ currentUser.updateTime }}</el-descriptions-item>
      </el-descriptions>
      
      <div v-if="currentUser.roles && currentUser.roles.length > 0" style="margin-top: 20px;">
        <h4>角色信息</h4>
        <el-tag
          v-for="role in currentUser.roles"
          :key="role.id"
          style="margin-right: 10px; margin-bottom: 10px;"
        >
          {{ role.roleName }}
        </el-tag>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { userApi } from '@/api/userManagement'
import { roleApi } from '@/api/roleManagement'
import { permissionMixin } from '@/utils/permission'

export default {
  name: 'UserManagement',
  mixins: [permissionMixin],
  data() {
    return {
      loading: false,
      tableData: [],
      selectedRows: [],
      searchForm: {
        keyword: '',
        department: '',
        status: ''
      },
      pagination: {
        page: 1,
        size: 10,
        total: 0
      },
      dialogVisible: false,
      detailDialogVisible: false,
      isEdit: false,
      dialogTitle: '新增用户',
      formData: {
        username: '',
        password: '',
        name: '',
        email: '',
        phone: '',
        department: '',
        position: '',
        employeeId: '',
        status: 1,
        roleIds: []
      },
      formRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 50, message: '用户名长度在3到50个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
        ]
      },
      roleOptions: [],
      currentUser: {}
    }
  },
  mounted() {
    this.loadData()
    this.loadRoleOptions()
  },
  methods: {
    // 加载数据
    async loadData() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.page,
          size: this.pagination.size,
          ...this.searchForm
        }
        console.log('发送请求参数:', params)
        const response = await userApi.getUsers(params)
        console.log('API响应:', response)
        
        if (response.code === 200) {
          this.tableData = response.data.content || []
          this.pagination.total = response.data.total || 0
          console.log('用户数据加载成功:', this.tableData)
        } else {
          this.$message.error(response.message || '加载数据失败')
        }
      } catch (error) {
        console.error('API调用失败:', error)
        this.$message.error('加载数据失败: ' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },

    // 加载角色选项
    async loadRoleOptions() {
      try {
        const response = await roleApi.getAllRolesTree()
        if (response.code === 200) {
          this.roleOptions = this.flattenRoles(response.data)
        }
      } catch (error) {
        console.error('加载角色选项失败:', error)
      }
    },

    // 扁平化角色树
    flattenRoles(roles) {
      let result = []
      roles.forEach(role => {
        result.push(role)
        if (role.children && role.children.length > 0) {
          result = result.concat(this.flattenRoles(role.children))
        }
      })
      return result
    },

    // 搜索
    handleSearch() {
      this.pagination.page = 1
      this.loadData()
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        keyword: '',
        department: '',
        status: ''
      }
      this.pagination.page = 1
      this.loadData()
    },

    // 新增
    handleAdd() {
      this.isEdit = false
      this.dialogTitle = '新增用户'
      this.formData = {
        username: '',
        password: '',
        name: '',
        email: '',
        phone: '',
        department: '',
        position: '',
        employeeId: '',
        status: 1,
        roleIds: []
      }
      this.dialogVisible = true
    },

    // 编辑
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑用户'
      this.formData = { ...row }
      this.dialogVisible = true
    },

    // 查看
    handleView(row) {
      this.currentUser = row
      this.detailDialogVisible = true
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确定要删除该用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await userApi.deleteUser(row.id)
          if (response.code === 200) {
            this.$message.success('删除成功')
            this.loadData()
          }
        } catch (error) {
          this.$message.error('删除失败')
        }
      })
    },

    // 切换状态
    handleToggleStatus(row) {
      const action = row.status === 1 ? '禁用' : '启用'
      this.$confirm(`确定要${action}该用户吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const newStatus = row.status === 1 ? 0 : 1
          const response = await userApi.updateUserStatus(row.id, newStatus)
          if (response.code === 200) {
            this.$message.success(`${action}成功`)
            this.loadData()
          }
        } catch (error) {
          this.$message.error(`${action}失败`)
        }
      })
    },

    // 批量启用
    handleBatchEnable() {
      this.handleBatchOperation('enable', '启用')
    },

    // 批量禁用
    handleBatchDisable() {
      this.handleBatchOperation('disable', '禁用')
    },

    // 批量删除
    handleBatchDelete() {
      this.handleBatchOperation('delete', '删除')
    },

    // 批量操作
    async handleBatchOperation(operation, operationName) {
      this.$confirm(`确定要${operationName}选中的用户吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const userIds = this.selectedRows.map(row => row.id)
          const response = await userApi.batchOperation({
            userIds,
            operation
          })
          if (response.code === 200) {
            this.$message.success(`${operationName}成功`)
            this.loadData()
          }
        } catch (error) {
          this.$message.error(`${operationName}失败`)
        }
      })
    },

    // 导出
    handleExport() {
      // 实现导出逻辑
      this.$message.info('导出功能待实现')
    },

    // 提交表单
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            let response
            if (this.isEdit) {
              response = await userApi.updateUser(this.formData.id, this.formData)
            } else {
              response = await userApi.createUser(this.formData)
            }
            if (response.code === 200) {
              this.$message.success(this.isEdit ? '更新成功' : '创建成功')
              this.dialogVisible = false
              this.loadData()
            }
          } catch (error) {
            this.$message.error(this.isEdit ? '更新失败' : '创建失败')
          }
        }
      })
    },

    // 关闭对话框
    handleDialogClose() {
      this.$refs.form.resetFields()
    },

    // 选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },

    // 分页大小变化
    handleSizeChange(size) {
      this.pagination.size = size
      this.pagination.page = 1
      this.loadData()
    },

    // 当前页变化
    handleCurrentChange(page) {
      this.pagination.page = page
      this.loadData()
    },

    // 权限检查方法已通过mixin提供
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  flex-direction: column;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-subtitle {
  font-size: 14px;
  opacity: 0.9;
  margin-top: 4px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.header-actions .el-button {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  backdrop-filter: blur(10px);
}

.header-actions .el-button:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
}

/* 搜索区域 */
.search-section {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-form {
  padding: 10px 0;
}

.search-form .el-form-item {
  margin-bottom: 16px;
}

/* 表格区域 */
.table-section {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 16px;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.data-table {
  border-radius: 4px;
  overflow: hidden;
}

.data-table .el-table__header {
  background-color: #fafafa;
}

.data-table .el-table__header th {
  background-color: #fafafa !important;
  color: #606266;
  font-weight: 600;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  margin-top: 16px;
  border-top: 1px solid #ebeef5;
}

/* 批量操作 */
.batch-actions {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(100%);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

.batch-card {
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid #e4e7ed;
}

.batch-content {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 8px 0;
}

.batch-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.batch-buttons {
  display: flex;
  gap: 8px;
}

/* 对话框优化 */
.el-dialog {
  border-radius: 8px;
}

.el-dialog__header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 20px 16px;
  border-radius: 8px 8px 0 0;
}

.el-dialog__title {
  color: white;
  font-weight: 600;
}

.el-dialog__headerbtn .el-dialog__close {
  color: white;
}

.el-dialog__body {
  padding: 24px;
}

/* 表单优化 */
.el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.el-input__inner,
.el-select .el-input__inner {
  border-radius: 4px;
  transition: all 0.3s ease;
}

.el-input__inner:focus,
.el-select .el-input__inner:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

/* 按钮优化 */
.el-button {
  border-radius: 4px;
  transition: all 0.3s ease;
}

.el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.el-button--primary:hover {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

/* 标签优化 */
.el-tag {
  border-radius: 4px;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-management {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .header-actions {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    width: 100%;
  }
  
  .table-toolbar {
    flex-direction: column;
    gap: 12px;
  }
  
  .batch-content {
    flex-direction: column;
    gap: 12px;
  }
  
  .batch-buttons {
    flex-wrap: wrap;
    justify-content: center;
  }
}

/* 加载状态优化 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(2px);
}

/* 表格行悬停效果 */
.data-table .el-table__row:hover {
  background-color: #f8f9ff !important;
}

/* 空状态优化 */
.el-table__empty-block {
  background-color: #fafafa;
  border-radius: 4px;
}

/* 滚动条优化 */
.data-table::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.data-table::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.data-table::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.data-table::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
